package com.xxxy.ljh.myapplication.nav;

import android.text.Editable;
import android.text.TextWatcher;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.google.android.material.snackbar.Snackbar;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.xxxy.ljh.myapplication.Adapter.ClubAdapter;
import com.xxxy.ljh.myapplication.CreateClubActivity;
import com.xxxy.ljh.myapplication.R;
import com.xxxy.ljh.myapplication.activity.login.LoginActivity;
import com.xxxy.ljh.myapplication.Dao.ClubDao;
import com.xxxy.ljh.myapplication.DaoImpl.ClubDaoImpl;
import com.xxxy.ljh.myapplication.model.Club;
import com.xxxy.ljh.myapplication.activity.detail.ClubDetailActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * 社团页面Fragment，用于展示社团列表和创建社团功能
 */
public class ClubFragment extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;
    private static final int LOGIN_REQUEST_CODE = 1001; // 添加请求码常量


    // UI组件
    private RecyclerView recyclerViewClubs;
    private SwipeRefreshLayout swipeRefreshLayout;
    private ClubAdapter clubAdapter;

    // 数据相关
    private List<Club> clubList;
    private ClubDao clubDao;

    public ClubFragment() {
        // Required empty public constructor
    }

    /**
     * 创建ClubFragment实例的工厂方法
     *
     * @param param1 参数1
     * @param param2 参数2
     * @return ClubFragment实例
     */
    public static ClubFragment newInstance(String param1, String param2) {
        ClubFragment fragment = new ClubFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        // 初始化数据
        clubList = new ArrayList<>();
        // clubDao将在onCreateView中初始化
    }
    // 在 onCreateView 方法中添加搜索功能

    /**
     * 设置搜索功能
     * @param view Fragment的根视图
     */
    private void setupSearchFunctionality(View view) {
        com.google.android.material.textfield.TextInputEditText editTextSearch =
                view.findViewById(R.id.editTextSearch);

        editTextSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 不需要实现
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 实时搜索
                filterClubs(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 不需要实现
            }
        });
    }

    /**
     * 根据关键词过滤社团
     * @param keyword 搜索关键词
     */
    private void filterClubs(String keyword) {
        try {
            List<Club> filteredClubs;
            if (keyword.isEmpty()) {
                filteredClubs = clubDao.getAllClubs();
            } else {
                filteredClubs = clubDao.searchClubs(keyword);
            }

            clubList.clear();
            clubList.addAll(filteredClubs);
            clubAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "搜索社团失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_club, container, false);

        // 初始化数据访问对象
        clubDao = new ClubDaoImpl(getContext());

        // 初始化UI组件
        initViews(view);

        // 设置下拉刷新
        setupSwipeRefresh();

        // 添加创建社团按钮的点击事件
        Button btnCreateClub = view.findViewById(R.id.btn_create_club);
        btnCreateClub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 检查用户是否登录
                if (isUserLoggedIn()) {
                    // 用户已登录，跳转到创建社团页面
                    navigateToCreateClub();
                } else {
                    // 用户未登录，提示需要登录并跳转到登录页面
                    Toast.makeText(getContext(), "请先登录后再创建社团", Toast.LENGTH_SHORT).show();
                    // 跳转到登录页面
                    navigateToLogin();
                }
            }
        });

        return view;
    }

    /**
     * 初始化视图组件
     * @param view Fragment的根视图
     */
    private void initViews(View view) {
        recyclerViewClubs = view.findViewById(R.id.recyclerViewClubs);
        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);

        // 设置RecyclerView
        clubAdapter = new ClubAdapter(clubList, new ClubAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Club club) {
                navigateToClubDetail(club);
            }
        });

        recyclerViewClubs.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerViewClubs.setAdapter(clubAdapter);
    }

    /**
     * 设置下拉刷新功能
     */
    private void setupSwipeRefresh() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadClubData();
            }
        });
    }

    /**
     * 从数据库加载社团数据
     */
    private void loadClubData() {
        // 立即设置刷新状态
        if (!swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(true);
        }

        try {
            clubList.clear();
            clubList.addAll(clubDao.getAllClubs());
            clubAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "加载社团数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            Log.e("ClubFragment", "加载社团数据失败", e);
        } finally {
            // 确保总是重置刷新状态
            if (swipeRefreshLayout != null && swipeRefreshLayout.isRefreshing()) {
                swipeRefreshLayout.setRefreshing(false);
            }
        }
    }

    /**
     * 跳转到登录页面
     */
    private void navigateToLogin() {
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivityForResult(intent, LOGIN_REQUEST_CODE);
    }

    /**
     * 检查用户是否已登录
     * @return true表示已登录，false表示未登录
     */
    private boolean isUserLoggedIn() {
        SharedPreferences prefs = getActivity().getSharedPreferences("user_prefs", getActivity().MODE_PRIVATE);
        return prefs.getBoolean("is_logged_in", false);
    }

    /**
     * 跳转到创建社团页面
     */
    private void navigateToCreateClub() {
        Intent intent = new Intent(getActivity(), CreateClubActivity.class);
        startActivity(intent);
    }

    /**
     * 跳转到社团详情页面
     * @param club 要查看的社团
     */
    private void navigateToClubDetail(Club club) {
        Intent intent = new Intent(getActivity(), ClubDetailActivity.class);
        intent.putExtra("association_id", club.getId());
        startActivity(intent);
    }

    @Override
    public void onResume() {
        super.onResume();
        // 每次页面可见时刷新数据
        if (clubDao != null && swipeRefreshLayout != null) {
            loadClubData();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LOGIN_REQUEST_CODE && resultCode == getActivity().RESULT_OK) {
            if (data != null) {
                String username = data.getStringExtra("logged_in_user");
                if (username != null && !username.isEmpty()) {
                    // 保存登录状态
                    SharedPreferences prefs = getActivity().getSharedPreferences("user_prefs", getActivity().MODE_PRIVATE);
                    prefs.edit()
                            .putBoolean("is_logged_in", true)
                            .putString("username", username)
                            .apply();

                    // 添加登录成功提示
                    Toast.makeText(getContext(), "登录成功", Toast.LENGTH_SHORT).show();

                    // 登录成功后自动跳转到创建社团页面
                    navigateToCreateClub();
                }
            }
        }
    }
    // 在 ClubFragment 中更新数据刷新逻辑
    private void refreshClubData() {
        try {
            List<Club> clubs = clubDao.getAllClubs();
            clubList.clear();
            clubList.addAll(clubs);
            clubAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            Log.e("ClubFragment", "加载社团数据失败", e);
            Toast.makeText(getContext(), "加载社团数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        } finally {
            if (swipeRefreshLayout != null && swipeRefreshLayout.isRefreshing()) {
                swipeRefreshLayout.setRefreshing(false);
            }
        }
    }

}
